<template>
    <div class="max-w-4xl mx-auto p-6">
        <div class="flex justify-between items-center mb-8">
            <h2 class="text-2xl font-bold text-gray-800">事件复盘</h2>
            <a-button type="primary" @click="showModal = true">
                添加事件
            </a-button>
        </div>
        <div class="h-[300px] relative">
            <div class="absolute left-6 top-0 bottom-0 w-0.5 bg-gray-200"></div>
            <div class="pl-12 h-full overflow-y-auto relative">
                <div v-for="(event, index) in events" :key="index" class="mb-6 relative">
                    <!-- 事件图标 -->
                    <div class="absolute -left-12 w-12 h-12 bg-white border-2 border-green-500 rounded-full flex items-center justify-center z-10">
                        <span class="text-xl">📅</span>
                    </div>
                    
                    <!-- 事件内容 -->
                    <div class="bg-white rounded-lg shadow-sm border border-gray-100">
                        <!-- 第一行：时间、名称 -->
                        <div class="flex items-center p-4">
                            <span class="text-sm text-gray-500 w-40">{{ event.time }}</span>
                            <span class="text-gray-800 font-medium">{{ event.name }}</span>
                        </div>
                        
                        <!-- 第二行：附件 -->
                        <div v-if="event.attachments && event.attachments.length" class="px-4 pb-4">
                            <div class="flex gap-4">
                                <div v-for="(attachment, aIndex) in event.attachments" :key="aIndex" 
                                     class="relative w-20 h-20 rounded overflow-hidden border border-gray-200">
                                    <img :src="attachment.url" :alt="attachment.name" 
                                         class="w-full h-full object-cover hover:opacity-90 transition-opacity cursor-pointer">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加事件弹窗 -->
    <a-modal
        v-model:visible="showModal"
        title="添加新事件"
        @ok="handleSubmit"
        @cancel="closeModal"
        :maskClosable="false"
    >
        <a-form
            :model="newEvent"
            :rules="rules"
            ref="formRef"
            layout="vertical"
        >
            <a-form-item label="事件时间" name="time">
                <a-date-picker
                    v-model:value="newEvent.time"
                    show-time
                    format="YYYY-MM-DD HH:mm"
                    style="width: 100%"
                />
            </a-form-item>

            <a-form-item label="事件名称" name="name">
                <a-input v-model:value="newEvent.name" placeholder="请输入事件名称" />
            </a-form-item>

            <a-form-item label="附件">
                <a-upload
                    v-model:file-list="fileList"
                    :headers="requestHeader"
                    :action="uploadUrl"
                    :before-upload="beforeUpload"
                    multiple
                    @change="handleUploadChange"
                >
                    <a-button>
                        <upload-outlined />
                        选择文件
                    </a-button>
                </a-upload>
            </a-form-item>
        </a-form>
    </a-modal>
</template>
    
<script setup lang='ts'>
import { ref, onMounted, onUnmounted } from 'vue';
import axios from 'axios';
import { message } from 'ant-design-vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import type { UploadProps } from 'ant-design-vue';
import dayjs from 'dayjs';
// import emitter from '@/utils/emitter';

interface Attachment {
    url: string;
    name: string;
}

interface Event {
    time: string;
    name: string;
    attachments?: Attachment[];
    eventId?: string;
}

const showModal = ref(false);
const formRef = ref();
const fileList = ref<any[]>([]);
const uploadUrl = '/api/upload'; // 你的上传接口地址
const requestHeader = {
    // 如果需要认证头，在这里添加
    // 'Authorization': 'Bearer xxx'
};

const newEvent = ref({
    time: '',
    name: '',
    attachments: [] as Attachment[]
});

const rules = {
    time: [{ required: true, message: '请选择事件时间' }],
    name: [{ required: true, message: '请输入事件名称' }]
};

const currentEventId = ref<string | null>(null);

onMounted(() => {
    emitter.on('eventId', (id: string) => {
        currentEventId.value = id;
    });
});

onUnmounted(() => {
    emitter.off('eventId');
});

const isShow = () => {
    if (currentEventId.value) {
        // 这里可以处理 currentEventId 的值
        console.log('当前事件ID:', currentEventId.value);
        // 如果需要调用其他方法，可以在这里调用
        // Getlist(currentEventId.value);
    }
    close();
}

const handleUploadChange = (info: any) => {
    fileList.value = info.fileList;
    
    // 更新 newEvent.attachments，收集所有文件ID
    newEvent.value.attachments = fileList.value
        .filter(file => file.status === 'done')
        .flatMap(file => file.response?.data?.map((item: any) => item.id) || []);
};

const beforeUpload: UploadProps['beforeUpload'] = (file) => {
    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
        message.error('文件大小不能超过 10MB!');
        return false;
    }
    return true;
};

const handleSubmit = async () => {
    try {
        await formRef.value.validate();
        
        // 确保所有文件都已上传完成
        const uploadingFiles = fileList.value.filter(file => file.status === 'uploading');
        if (uploadingFiles.length > 0) {
            message.warning('请等待文件上传完成');
            return;
        }

        if (!currentEventId.value) {
            message.error('获取事件ID失败');
            return;
        }

        // 创建新事件
        const event: Event = {
            time: dayjs(newEvent.value.time).format('YYYY-MM-DD HH:mm'),
            name: newEvent.value.name,
            attachments: newEvent.value.attachments,
            eventId: currentEventId.value
        };

        // 添加到事件列表
        events.push(event);

        // 重置表单并关闭弹窗
        formRef.value.resetFields();
        fileList.value = [];
        showModal.value = false;
        message.success('添加事件成功');
    } catch (error) {
        console.error('保存事件失败:', error);
    }
};

const closeModal = () => {
    showModal.value = false;
    formRef.value?.resetFields();
    fileList.value = [];
    newEvent.value.attachments = [];
};

// 示例数据
const events = [
    {
        time: '2024-03-20 10:00',
        name: '项目启动会议',
        attachments: [
            {
                url: 'https://picsum.photos/200/200?random=1',
                name: '会议纪要'
            },
            {
                url: 'https://picsum.photos/200/200?random=2',
                name: '项目计划'
            }
        ]
    },
    {
        time: '2024-03-21 14:30',
        name: '需求分析完成',
        attachments: [
            {
                url: 'https://picsum.photos/200/200?random=3',
                name: '需求文档'
            }
        ]
    },
    {
        time: '2024-03-22 09:15',
        name: '开发环境搭建'
    },
    {
        time: '2024-03-23 16:00',
        name: '第一阶段开发完成',
        attachments: [
            {
                url: 'https://picsum.photos/200/200?random=4',
                name: '开发进度报告'
            }
        ]
    }
];
</script>

<style scoped>
:deep(.ant-upload-list-item) {
    margin-top: 8px;
}
</style>